package gcu.module.owner.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import gcu.module.owner.dao.OwnerDao;
import gcu.module.owner.daomain.Owner;
import gcu.module.owner.daomain.OwnerImport;
import gcu.module.room.dao.RoomDao;
import gcu.module.room.daomain.Room;
import gcu.util.Identities;
import gcu.util.SFormt;
import gcu.util.ExcelHandleUtil;
import gcu.util.UploadStatus;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by haol on 2016/9/28.
 */
@Service
public class UploadService {

      private Logger logger = LoggerFactory.getLogger(UploadService.class);

      @Autowired
      private RoomDao roomDao;
      @Autowired
      private OwnerService ownerService;
      /**
       * 上传文件
       *
       * @param file
       * @param uploadDir
       * @param model
       * @return
       */
      public Map<String, Object> handleFiles(MultipartFile file, String uploadDir, Model model) {
            Map<String, Object> map = Maps.newHashMap();
            List<OwnerImport> records = Lists.newArrayList();
            //封装解析的excel内容
            //上传模版文件列头
            String[] columns = {"业主姓名", "楼宇号", "房间号", "联系电话", "性别", "家庭人数", "工作单位"};
            String[] properties = {"ownerName", "buildName", "roomNum", "phone", "sex", "homeNum", "unitAdd"};
            Class[] classes = {String.class, String.class, String.class, String.class, String.class, String.class, String.class};
            UploadStatus uploadStatus = ExcelHandleUtil.handleFile(file, uploadDir,
                    columns, properties, classes,
                    records, OwnerImport.class);
            if (uploadStatus == UploadStatus.SUCCESS) {
                  map.put("id", uploadStatus.id());
                  map.put("desc", uploadStatus.desc());/*自定义的错误*/
                  if (records != null && records.size() > 0) {
                        List<OwnerImport> error = this.bussinessCheck(records);

                        StringBuffer uploaderror = new StringBuffer();
                        for (int i = 0; i < error.size(); i++) {
                              uploaderror.append("<br/>");
                              uploaderror.append("【错误[" + i + "]】:");
                              uploaderror.append(error.get(i).getErrorMessage().substring(4, error.get(i).getErrorMessage().length() - 1));
                        }
                        map.put("updateError", uploaderror);
                        map.put("total", records.size());
                        map.put("num", records.size() - error.size());
                  }
            } else {
                  map.put("id", uploadStatus.id());
                  map.put("desc", uploadStatus.desc());
            }
            return map;
      }

      /**
       * /**
       * 对上传成功的数据进行封装在List<ChumImport> 中进行数据业务校验，此处接受到的是上传成功的文件，喂！未校验是否合格
       *
       * @param
       * @return
       */
      public List<OwnerImport> bussinessCheck(List<OwnerImport> ownerImports) {
            List<OwnerImport> error = new ArrayList<OwnerImport>();
            for (OwnerImport ownerImport : ownerImports) {
                  try {
                        ownerImport = requiredIsNull(ownerImport);//非空校验
                        ownerImport = fieldIsSuit(ownerImport);//唯一性校验
                        ownerImport = RoomIsNotIn(ownerImport);//宿舍是否存在且未住满
                  } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                  }
                  if (StringUtils.isBlank(ownerImport.getErrorMessage())) {
                        Owner owner = new Owner();
                        owner.setOwnerName(ownerImport.getOwnerName());
                        owner.setBuildName(ownerImport.getBuildName());
                        owner.setRoomNum(ownerImport.getRoomNum());
                        owner.setHomeNum(ownerImport.getHomeNum());
                        owner.setPhone(ownerImport.getPhone());
                        owner.setUnitAdd(ownerImport.getUnitAdd());
                        if (ownerImport.getSex().equals("男")) {
                              owner.setSex(1);
                        } else {
                              owner.setSex(0);
                        }
                        owner.setCreateTime(SFormt.NOWDATE_y_M_dhms());
                        ownerService.add(owner);
                  } else {
                        error.add(ownerImport);
                        logger.error(ownerImport.getErrorMessage().substring(0,ownerImport.getErrorMessage().length()-1));
                  }
            }
            return error;
      }

      public OwnerImport requiredIsNull(OwnerImport ownerImport) {
            if (StringUtils.isBlank(ownerImport.getOwnerName())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "业主姓名不能为空,");
            }
            if (StringUtils.isBlank(ownerImport.getBuildName())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "楼宇信息不能为空,");
            }
            if (StringUtils.isBlank(ownerImport.getRoomNum())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "房间号不能为空,");
            }
            if (StringUtils.isBlank(ownerImport.getHomeNum())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "家庭人数不能为空,");
            }
            if (StringUtils.isBlank(ownerImport.getSex())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "性别不能为空,");
            }
            if (StringUtils.isBlank(ownerImport.getPhone())) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "联系电话不能为空,");
            }
            return ownerImport;
      }

      public OwnerImport fieldIsSuit(OwnerImport ownerImport) {
            if (!((ownerImport.getSex().equals("男")) || (ownerImport.getSex().equals("女")))) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "业主性别填写有误,");
            }
            Pattern patternNum = Pattern.compile("[0-9]*");
            Matcher roomNum = patternNum.matcher(ownerImport.getRoomNum());
            Matcher homeNum = patternNum.matcher(ownerImport.getRoomNum());

           if (StringUtils.isNotBlank(ownerImport.getRoomNum())){
                 if (!roomNum.matches() || Integer.parseInt(ownerImport.getRoomNum()) < 0) {
                       ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "房间号填写有误,");
                 }
           }
            if (StringUtils.isNotBlank(ownerImport.getRoomNum())){
                  if (!homeNum.matches() || Integer.parseInt(ownerImport.getRoomNum()) < 0) {
                        ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "家庭人数填写有误,");
                  }
            }

            Pattern patternPhone = Pattern.compile("^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$");
            Pattern patternTel = Pattern.compile("^\\d{3,4}-?\\d{7,9}$");
            Matcher phone = patternPhone.matcher(ownerImport.getPhone());
            Matcher tel = patternTel.matcher(ownerImport.getPhone());

            if (StringUtils.isNotBlank(ownerImport.getPhone())) {
                  if (!phone.matches() && !tel.matches()) {
                        ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "联系电话填写有误,");
                  }
            }
            return ownerImport;
      }

      public OwnerImport RoomIsNotIn(OwnerImport ownerImport) {
            Room room = roomDao.queryRoomByNameAndBuildName(ownerImport.getBuildName(), ownerImport.getRoomNum());
            if (room == null) {
                  ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "填写的楼宇和房间信息有误,");
            } else {
                  if (room.getIsIn() == 1) {
                        ownerImport.setErrorMessage(ownerImport.getErrorMessage() + "填写的楼宇和房间已经有分配,");
                  }
            }
            return ownerImport;
      }
}
